package com.aijle.videopaper.service;

import android.accessibilityservice.AccessibilityService;
import android.annotation.TargetApi;
import android.app.ActivityManager;
import android.app.Notification;
import android.app.NotificationChannel;
import android.app.NotificationManager;
import android.app.Service;
import android.app.usage.UsageStats;
import android.app.usage.UsageStatsManager;
import android.content.ComponentName;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.content.pm.ActivityInfo;
import android.content.pm.PackageManager;
import android.content.pm.ResolveInfo;
import android.graphics.PixelFormat;
import android.graphics.Point;
import android.hardware.Sensor;
import android.hardware.SensorEvent;
import android.hardware.SensorEventListener;
import android.hardware.SensorManager;
import android.os.Build;
import android.os.Handler;
import android.os.IBinder;
import android.provider.Settings;
import android.util.Log;
import android.view.Gravity;
import android.view.View;
import android.view.WindowManager;
import android.view.accessibility.AccessibilityEvent;
import android.widget.FrameLayout;

import com.aijle.videopaper.R;
import com.aijle.videopaper.receiver.LaunchReceiver;
import com.aijle.videopaper.receiver.OverlayReceiver;
import com.aijle.videopaper.util.IOverlay;
import com.aijle.videopaper.util.NotificationUtil;
import com.aijle.videopaper.util.OverlayHelper;
import com.aijle.videopaper.util.Preferences;
import com.aijle.videopaper.util.Util;
import com.aijle.videopaper.util.WindowWidgetManager;
import com.rvalerio.fgchecker.AppChecker;

import org.dync.ijkplayerlib.widget.media.IRenderView;
import org.dync.ijkplayerlib.widget.media.IjkVideoView;

import java.lang.reflect.Field;
import java.util.Date;
import java.util.List;
import java.util.SortedMap;
import java.util.Timer;
import java.util.TimerTask;
import java.util.TreeMap;

import tv.danmaku.ijk.media.player.IMediaPlayer;

import static android.view.View.SYSTEM_UI_FLAG_LOW_PROFILE;

public class OverlayService extends Service implements IOverlay {
    public static final String TAG = "OverlayService";

    /**
     * 通知栏ID
     */
    public static final int NOTIFICATION_ID = 0x1000;

    /**
     * 广播接收器
     */
    private OverlayReceiver mReceiver;
    private LaunchReceiver mLaunchReceiver;

    private static final long INTERVAL = 1000;
    private Handler handler = new Handler();
    private Timer mTimer;
    /**
     * 通知栏管理器
     */
    private NotificationManager mNotificationManager;
    OverlayHelper mOverlayHelper;

    @Override
    public void playNext() {
        mOverlayHelper.playNext();
    }

    @Override
    public void reload() {
        mOverlayHelper.reload();

        if (mOverlayHelper.isShowDesktop()) {
            if (mTimer != null) {
                mTimer.cancel();
                mTimer = null;
            }
            mOverlayHelper.setCanShow(true);
        } else {
            if (mTimer == null) {
                mTimer = new Timer();
                mTimer.scheduleAtFixedRate(new CheckTask(), 0, INTERVAL);
            }
        }
    }

    @Override
    public void toggle() {
        mOverlayHelper.toggle();
    }

    @Override
    public void open() {
        mOverlayHelper.open();
    }

    @Override
    public void close() {
        mOverlayHelper.close();
    }

    @Override
    public void updateLayout() {
        mOverlayHelper.updateLayout();
    }

    @Override
    public void switchSound() {
        mOverlayHelper.switchSound();
    }

    @Override
    public void updateVolume() {
        mOverlayHelper.updateVolume();
    }

    @Override
    public void updateXPos() {
        mOverlayHelper.updateXPos();
    }

    @Override
    public void updateSensor(boolean stop) {
        updateSensor(stop, true);
    }

    public void updateSensor(boolean stop, boolean resetx) {
        mOverlayHelper.updateSensor(stop, resetx);
    }

    @Override
    public void pause() {
        mOverlayHelper.pause();
    }

    @Override
    public void resume() {
        mOverlayHelper.resume();
    }

    /**
     * 添加通知
     */
    private void addNotification() {
        // 获取通知管理器
        mNotificationManager = (NotificationManager) getSystemService(Context.NOTIFICATION_SERVICE);
        // Android O以上需要配置通知渠道
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
            NotificationChannel channel = new NotificationChannel(NotificationUtil.CHANNEL_ID, NotificationUtil.CHANNEL_NAME, NotificationManager.IMPORTANCE_DEFAULT);
            mNotificationManager.createNotificationChannel(channel);
        }
        // 获取Notification实例
        Notification notification = NotificationUtil.getNotificationByVersion(this);
        // 将辅助服务设置为前台服务
        startForeground(NOTIFICATION_ID, notification);
        // 显示Notification
        if (mNotificationManager != null) {
            mNotificationManager.notify(NOTIFICATION_ID, notification);
        }
    }

    @Override
    public void onCreate() {
        super.onCreate();

        WindowWidgetManager widgetManager = new WindowWidgetManager(this);
        mOverlayHelper = new OverlayHelper(this, widgetManager);

        // 添加通知栏消息（将服务提升到前台）
        addNotification();
        // 注册广播接收器
        mReceiver = new OverlayReceiver();
        IntentFilter intentFilter = new IntentFilter();
        intentFilter.addAction(OverlayReceiver.SWITCH_ACTION);
        intentFilter.addAction(OverlayReceiver.UPDATE_ACTION);
        intentFilter.addAction(Intent.ACTION_SCREEN_OFF);
        intentFilter.addAction(Intent.ACTION_SCREEN_ON);
        registerReceiver(mReceiver, intentFilter);

//        Intent intent = new Intent(Intent.ACTION_MAIN);
//        intent.addCategory(Intent.CATEGORY_HOME);
//        ResolveInfo resolveInfo = getPackageManager().resolveActivity(intent, 0);
//        String currentHomePackage = resolveInfo.activityInfo.packageName;
//
//        Log.d(TAG, currentHomePackage);
//        mLaunchReceiver = new LaunchReceiver();
//        IntentFilter intentFilter2 = new IntentFilter();
//        intentFilter2.addAction(Intent.ACTION_MAIN);
//        intentFilter2.addCategory(Intent.CATEGORY_LAUNCHER);
//        registerReceiver(mLaunchReceiver, intentFilter2);

        reload();
    }

    public void showDesktop() {

    }

    public void hideDesktop() {

    }

    private class CheckTask extends TimerTask {

        @Override
        public void run() {
            handler.post(runnable);
        }
    }

    public static String getTopAppInfoPackageName(Context context) {
        if (Build.VERSION.SDK_INT < 21) { // 如果版本低于22
            // 获取到activity的管理的类
            ActivityManager m = (ActivityManager) context.getSystemService(Context.ACTIVITY_SERVICE);
            // 获取最近的一个运行的任务的信息
            List<ActivityManager.RunningTaskInfo> tasks = m.getRunningTasks(1);

            if (tasks != null && tasks.size() > 0) { // 如果集合不是空的

                // 返回任务栈中最上面的一个
                ActivityManager.RunningTaskInfo info = m.getRunningTasks(1).get(0);

                // 获取到应用的包名
                // String packageName =
                // info.topActivity.getPackageName();
                return info.baseActivity.getPackageName();
            } else {
                return "";
            }
        } else {

            final int PROCESS_STATE_TOP = 2;
            try {
                // 获取正在运行的进程应用的信息实体中的一个字段,通过反射获取出来
                Field processStateField = ActivityManager.RunningAppProcessInfo.class.getDeclaredField("processState");
                // 获取所有的正在运行的进程应用信息实体对象
                List<ActivityManager.RunningAppProcessInfo> processes = ((ActivityManager) context
                        .getSystemService(Context.ACTIVITY_SERVICE)).getRunningAppProcesses();
                // 循环所有的进程,检测某一个进程的状态是最上面,也是就最近运行的一个应用的状态的时候,就返回这个应用的包名
                for (ActivityManager.RunningAppProcessInfo process : processes) {
                    if (process.importance <= ActivityManager.RunningAppProcessInfo.IMPORTANCE_FOREGROUND
                            && process.importanceReasonCode == 0) {
                        int state = processStateField.getInt(process);
                        if (state == PROCESS_STATE_TOP) { // 如果这个实体对象的状态为最近的运行应用
                            String[] packname = process.pkgList;
                            // 返回应用的包名
                            return packname[0];
                        }
                    }
                }
            } catch (Exception e) {
            }
            return "";
        }
    }

    AppChecker appChecker = new AppChecker();

    private Runnable runnable = new Runnable() {
        @Override
        public void run() {
//            String packname = getTopAppInfoPackageName(OverlayService.this);
//            Log.d(TAG, packname);
//
//            ActivityManager mActivityManager = (ActivityManager) getSystemService(Context.ACTIVITY_SERVICE);
//            List<ActivityManager.RunningTaskInfo> rti = mActivityManager.getRunningTasks(1);
//            Log.d(TAG, rti.get(0).topActivity.getPackageName());

            String packageName = appChecker.getForegroundApp(OverlayService.this);
            if (packageName == null)
                return;
//            Log.d(TAG, packageName);

            Intent intent = new Intent(Intent.ACTION_MAIN);
            intent.addCategory(Intent.CATEGORY_HOME);
            ResolveInfo resolveInfo = getPackageManager().resolveActivity(intent, 0);
            String currentHomePackage = resolveInfo.activityInfo.packageName;
//            Log.d(TAG, currentHomePackage);

            if (currentHomePackage.compareTo(packageName) == 0) {
                mOverlayHelper.setCanShow(false);
            } else {
                mOverlayHelper.setCanShow(true);
            }

//            ActivityManager activityManager = (ActivityManager) OverlayService.this.getSystemService( Context.ACTIVITY_SERVICE );
//            List<ActivityManager.RunningAppProcessInfo> appProcesses = activityManager.getRunningAppProcesses();
//            for(ActivityManager.RunningAppProcessInfo appProcess : appProcesses){
//                if(appProcess.importance == ActivityManager.RunningAppProcessInfo.IMPORTANCE_FOREGROUND){
//                    Log.i("Foreground App", appProcess.processName);
//                }
//            }
        }
    };

    @Override
    public int onStartCommand(Intent intent, int flags, int startId) {
        super.onStartCommand(intent, flags, startId);
        return START_STICKY;
    }

    /**
     * 服务退出
     */
    @Override
    public void onDestroy() {
        Log.d(TAG, "onDestroy");

        if (mTimer != null) {
            mTimer.cancel();
        }
        // 取消通知栏消息显示
        if (mNotificationManager != null) {
            mNotificationManager.cancel(NOTIFICATION_ID);
            mNotificationManager = null;
        }
        // 解注册广播接收器
        if (mReceiver != null) {
            unregisterReceiver(mReceiver);
            mReceiver = null;
        }

//        if (mLaunchReceiver != null) {
//            unregisterReceiver(mLaunchReceiver);
//            mLaunchReceiver = null;
//        }
        // 停止前台服务
        stopForeground(true);
        super.onDestroy();
    }

    @Override
    public IBinder onBind(Intent intent) {
        return null;
    }
}
